<template>
  <view class="login-container">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="navbar-content">
        <u-icon 
          v-if="canGoBack" 
          name="arrow-left" 
          size="20" 
          color="#333" 
          @click="goBack"
        ></u-icon>
        <text class="navbar-title">登录</text>
        <view class="navbar-right"></view>
      </view>
    </view>
    
    <!-- 主要内容区域 -->
    <view class="main-content">
      <!-- Logo和标题 -->
      <view class="header-section">
        <image class="app-logo" src="/static/logo.png" mode="aspectFit"></image>
        <text class="app-title">母婴AI助手</text>
        <text class="app-subtitle">您的专属智能育儿顾问</text>
      </view>
      
      <!-- 登录方式选择 -->
      <view class="login-methods">
        <!-- 手机号登录 -->
        <view v-if="loginType === 'phone'" class="phone-login">
          <view class="input-group">
            <u-input 
              v-model="phoneNumber"
              type="number"
              placeholder="请输入手机号"
              maxlength="11"
              :border="true"
              :clearable="true"
              prefix-icon="phone"
              @input="onPhoneInput"
            ></u-input>
          </view>
          
          <view class="input-group">
            <u-input 
              v-model="verifyCode"
              type="number"
              placeholder="请输入验证码"
              maxlength="6"
              :border="true"
              :clearable="true"
              prefix-icon="lock"
            >
              <template #suffix>
                <u-button 
                  :text="codeButtonText"
                  type="primary"
                  size="mini"
                  :disabled="!canSendCode || codeCountdown > 0"
                  @click="sendVerifyCode"
                ></u-button>
              </template>
            </u-input>
          </view>
          
          <u-button 
            class="login-button"
            type="primary"
            size="large"
            :loading="loginLoading"
            :disabled="!canLogin"
            @click="phoneLogin"
          >
            登录
          </u-button>
        </view>
        
        <!-- 小程序授权登录 -->
        <!-- #ifdef MP-WEIXIN -->
        <view class="wechat-login">
          <u-button 
            class="wechat-login-btn"
            type="success"
            size="large"
            :loading="wechatLoading"
            open-type="getUserInfo"
            @getuserinfo="wechatLogin"
          >
            <u-icon name="wechat-fill" size="20" color="white" style="margin-right: 10rpx;"></u-icon>
            微信快速登录
          </u-button>
        </view>
        <!-- #endif -->
        
        <!-- #ifdef MP-TOUTIAO -->
        <view class="toutiao-login">
          <u-button 
            class="toutiao-login-btn"
            type="warning"
            size="large"
            :loading="toutiaoLoading"
            @click="toutiaoLogin"
          >
            <u-icon name="star-fill" size="20" color="white" style="margin-right: 10rpx;"></u-icon>
            抖音快速登录
          </u-button>
        </view>
        <!-- #endif -->
        
        <!-- #ifdef MP-XHS -->
        <view class="xhs-login">
          <u-button 
            class="xhs-login-btn"
            type="error"
            size="large"
            :loading="xhsLoading"
            @click="xhsLogin"
          >
            <u-icon name="heart-fill" size="20" color="white" style="margin-right: 10rpx;"></u-icon>
            小红书快速登录
          </u-button>
        </view>
        <!-- #endif -->
        
        <!-- 登录方式切换 -->
        <view class="login-switch">
          <text 
            class="switch-text"
            @click="switchLoginType"
          >
            {{ loginType === 'phone' ? '使用平台账号登录' : '使用手机号登录' }}
          </text>
        </view>
      </view>
      
      <!-- 协议同意 -->
      <view class="agreement-section">
        <view class="agreement-checkbox" @click="toggleAgreement">
          <u-icon 
            :name="agreedToTerms ? 'checkbox-mark' : 'checkbox'" 
            size="16" 
            :color="agreedToTerms ? '#007aff' : '#c0c0c0'"
          ></u-icon>
          <text class="agreement-text">
            我已阅读并同意
            <text class="agreement-link" @click.stop="viewTerms">《用户协议》</text>
            和
            <text class="agreement-link" @click.stop="viewPrivacy">《隐私政策》</text>
          </text>
        </view>
      </view>
      
      <!-- 游客模式 -->
      <view class="guest-section">
        <text class="guest-text" @click="guestLogin">暂不登录，先体验一下</text>
      </view>
    </view>
    
    <!-- 底部装饰 -->
    <view class="footer-decoration">
      <image class="decoration-image" src="/static/login-decoration.png" mode="aspectFit"></image>
    </view>
  </view>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { post } from '@/utils/request';

// 登录响应接口
interface LoginResponse {
  token: string;
  userInfo: {
    id: string;
    phone: string;
    nickname: string;
    avatar?: string;
    membershipType: string;
  };
}

@Component
export default class LoginPage extends Vue {
  // 数据属性
  statusBarHeight: number = 0;
  canGoBack: boolean = false;
  loginType: 'phone' | 'platform' = 'platform';
  
  // 手机号登录相关
  phoneNumber: string = '';
  verifyCode: string = '';
  codeCountdown: number = 0;
  codeTimer: any = null;
  
  // 加载状态
  loginLoading: boolean = false;
  wechatLoading: boolean = false;
  toutiaoLoading: boolean = false;
  xhsLoading: boolean = false;
  
  // 协议同意状态
  agreedToTerms: boolean = false;
  
  // 计算属性
  get canSendCode(): boolean {
    return /^1[3-9]\d{9}$/.test(this.phoneNumber);
  }
  
  get canLogin(): boolean {
    return this.canSendCode && 
           this.verifyCode.length === 6 && 
           this.agreedToTerms;
  }
  
  get codeButtonText(): string {
    return this.codeCountdown > 0 ? `${this.codeCountdown}s` : '获取验证码';
  }
  
  // 生命周期
  onLoad(options: any) {
    this.initPage();
    
    // 检查是否可以返回
    const pages = getCurrentPages();
    this.canGoBack = pages.length > 1;
  }
  
  onUnload() {
    if (this.codeTimer) {
      clearInterval(this.codeTimer);
    }
  }
  
  // 方法
  
  /**
   * 初始化页面
   */
  initPage() {
    // 获取系统信息
    const systemInfo = uni.getSystemInfoSync();
    this.statusBarHeight = systemInfo.statusBarHeight || 0;
    
    // 检查是否已登录
    const token = uni.getStorageSync('token');
    if (token) {
      this.redirectToMain();
    }
  }
  
  /**
   * 返回上一页
   */
  goBack() {
    uni.navigateBack();
  }
  
  /**
   * 切换登录方式
   */
  switchLoginType() {
    this.loginType = this.loginType === 'phone' ? 'platform' : 'phone';
  }
  
  /**
   * 手机号输入处理
   */
  onPhoneInput(value: string) {
    // 自动格式化手机号
    this.phoneNumber = value.replace(/\D/g, '').slice(0, 11);
  }
  
  /**
   * 发送验证码
   */
  async sendVerifyCode() {
    if (!this.canSendCode) {
      uni.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }
    
    try {
      await post('/auth/send-code', {
        phone: this.phoneNumber
      });
      
      uni.showToast({
        title: '验证码已发送',
        icon: 'success'
      });
      
      // 开始倒计时
      this.startCountdown();
      
    } catch (error) {
      console.error('发送验证码失败:', error);
      uni.showToast({
        title: '发送失败，请重试',
        icon: 'none'
      });
    }
  }
  
  /**
   * 开始倒计时
   */
  startCountdown() {
    this.codeCountdown = 60;
    this.codeTimer = setInterval(() => {
      this.codeCountdown--;
      if (this.codeCountdown <= 0) {
        clearInterval(this.codeTimer);
        this.codeTimer = null;
      }
    }, 1000);
  }
  
  /**
   * 手机号登录
   */
  async phoneLogin() {
    if (!this.canLogin) {
      uni.showToast({
        title: '请完善登录信息',
        icon: 'none'
      });
      return;
    }
    
    this.loginLoading = true;
    
    try {
      const response = await post<LoginResponse>('/auth/login', {
        phone: this.phoneNumber,
        code: this.verifyCode,
        platform: this.getPlatform()
      });
      
      // 保存登录信息
      await this.saveLoginInfo(response.data);
      
      uni.showToast({
        title: '登录成功',
        icon: 'success'
      });
      
      // 跳转到主页
      this.redirectToMain();
      
    } catch (error) {
      console.error('登录失败:', error);
      uni.showToast({
        title: '登录失败，请重试',
        icon: 'none'
      });
    } finally {
      this.loginLoading = false;
    }
  }
  
  /**
   * 微信登录
   */
  // #ifdef MP-WEIXIN
  async wechatLogin(e: any) {
    if (!this.agreedToTerms) {
      uni.showToast({
        title: '请先同意用户协议',
        icon: 'none'
      });
      return;
    }
    
    if (e.detail.errMsg !== 'getUserInfo:ok') {
      uni.showToast({
        title: '授权失败',
        icon: 'none'
      });
      return;
    }
    
    this.wechatLoading = true;
    
    try {
      // 获取登录凭证
      const loginRes = await new Promise((resolve, reject) => {
        uni.login({
          success: resolve,
          fail: reject
        });
      }) as any;
      
      // 发送到服务器验证
      const response = await post<LoginResponse>('/auth/wechat-login', {
        code: loginRes.code,
        userInfo: e.detail.userInfo,
        platform: 'mp-weixin'
      });
      
      // 保存登录信息
      await this.saveLoginInfo(response.data);
      
      uni.showToast({
        title: '登录成功',
        icon: 'success'
      });
      
      this.redirectToMain();
      
    } catch (error) {
      console.error('微信登录失败:', error);
      uni.showToast({
        title: '登录失败，请重试',
        icon: 'none'
      });
    } finally {
      this.wechatLoading = false;
    }
  }
  // #endif
  
  /**
   * 抖音登录
   */
  // #ifdef MP-TOUTIAO
  async toutiaoLogin() {
    if (!this.agreedToTerms) {
      uni.showToast({
        title: '请先同意用户协议',
        icon: 'none'
      });
      return;
    }
    
    this.toutiaoLoading = true;
    
    try {
      // 获取抖音登录凭证
      const loginRes = await new Promise((resolve, reject) => {
        uni.login({
          success: resolve,
          fail: reject
        });
      }) as any;
      
      // 发送到服务器验证
      const response = await post<LoginResponse>('/auth/toutiao-login', {
        code: loginRes.code,
        platform: 'mp-toutiao'
      });
      
      // 保存登录信息
      await this.saveLoginInfo(response.data);
      
      uni.showToast({
        title: '登录成功',
        icon: 'success'
      });
      
      this.redirectToMain();
      
    } catch (error) {
      console.error('抖音登录失败:', error);
      uni.showToast({
        title: '登录失败，请重试',
        icon: 'none'
      });
    } finally {
      this.toutiaoLoading = false;
    }
  }
  // #endif
  
  /**
   * 小红书登录
   */
  // #ifdef MP-XHS
  async xhsLogin() {
    if (!this.agreedToTerms) {
      uni.showToast({
        title: '请先同意用户协议',
        icon: 'none'
      });
      return;
    }
    
    this.xhsLoading = true;
    
    try {
      // 获取小红书登录凭证
      const loginRes = await new Promise((resolve, reject) => {
        uni.login({
          success: resolve,
          fail: reject
        });
      }) as any;
      
      // 发送到服务器验证
      const response = await post<LoginResponse>('/auth/xhs-login', {
        code: loginRes.code,
        platform: 'mp-xhs'
      });
      
      // 保存登录信息
      await this.saveLoginInfo(response.data);
      
      uni.showToast({
        title: '登录成功',
        icon: 'success'
      });
      
      this.redirectToMain();
      
    } catch (error) {
      console.error('小红书登录失败:', error);
      uni.showToast({
        title: '登录失败，请重试',
        icon: 'none'
      });
    } finally {
      this.xhsLoading = false;
    }
  }
  // #endif
  
  /**
   * 游客登录
   */
  guestLogin() {
    // 设置游客标识
    uni.setStorageSync('isGuest', true);
    uni.setStorageSync('userInfo', {
      id: 'guest_' + Date.now(),
      nickname: '游客用户',
      membershipType: 'guest'
    });
    
    uni.showToast({
      title: '进入体验模式',
      icon: 'success'
    });
    
    this.redirectToMain();
  }
  
  /**
   * 保存登录信息
   */
  async saveLoginInfo(loginData: LoginResponse) {
    // 保存token
    uni.setStorageSync('token', loginData.token);
    
    // 保存用户信息
    uni.setStorageSync('userInfo', loginData.userInfo);
    
    // 清除游客标识
    uni.removeStorageSync('isGuest');
  }
  
  /**
   * 跳转到主页
   */
  redirectToMain() {
    uni.reLaunch({
      url: '/pages/index/index'
    });
  }
  
  /**
   * 切换协议同意状态
   */
  toggleAgreement() {
    this.agreedToTerms = !this.agreedToTerms;
  }
  
  /**
   * 查看用户协议
   */
  viewTerms() {
    uni.navigateTo({
      url: '/pages/webview/webview?url=' + encodeURIComponent('https://your-domain.com/terms') + '&title=' + encodeURIComponent('用户协议')
    });
  }
  
  /**
   * 查看隐私政策
   */
  viewPrivacy() {
    uni.navigateTo({
      url: '/pages/webview/webview?url=' + encodeURIComponent('https://your-domain.com/privacy') + '&title=' + encodeURIComponent('隐私政策')
    });
  }
  
  /**
   * 获取当前平台
   */
  getPlatform(): string {
    // #ifdef MP-WEIXIN
    return 'mp-weixin';
    // #endif
    // #ifdef MP-TOUTIAO
    return 'mp-toutiao';
    // #endif
    // #ifdef MP-XHS
    return 'mp-xhs';
    // #endif
    // #ifdef APP-PLUS
    return 'app-plus';
    // #endif
    // #ifdef H5
    return 'h5';
    // #endif
    return 'unknown';
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
}

.custom-navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  background-color: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  
  .navbar-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 88rpx;
    padding: 0 30rpx;
    
    .navbar-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
    }
    
    .navbar-right {
      width: 40rpx;
    }
  }
}

.main-content {
  padding: 200rpx 60rpx 100rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.header-section {
  text-align: center;
  margin-bottom: 100rpx;
  
  .app-logo {
    width: 160rpx;
    height: 160rpx;
    border-radius: 32rpx;
    margin-bottom: 40rpx;
    box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
  }
  
  .app-title {
    display: block;
    font-size: 48rpx;
    font-weight: 700;
    color: white;
    margin-bottom: 20rpx;
    text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
  }
  
  .app-subtitle {
    display: block;
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.8);
    text-shadow: 0 1rpx 4rpx rgba(0, 0, 0, 0.2);
  }
}

.login-methods {
  width: 100%;
  
  .phone-login {
    .input-group {
      margin-bottom: 30rpx;
      
      ::v-deep .u-input {
        background-color: rgba(255, 255, 255, 0.95);
        border-radius: 25rpx;
        padding: 0 30rpx;
        
        .u-input__content {
          padding: 25rpx 0;
        }
      }
    }
    
    .login-button {
      width: 100%;
      height: 100rpx;
      border-radius: 50rpx;
      font-size: 36rpx;
      font-weight: 600;
      margin-top: 40rpx;
      box-shadow: 0 8rpx 24rpx rgba(0, 122, 255, 0.3);
    }
  }
  
  .wechat-login,
  .toutiao-login,
  .xhs-login {
    margin-bottom: 30rpx;
    
    .wechat-login-btn,
    .toutiao-login-btn,
    .xhs-login-btn {
      width: 100%;
      height: 100rpx;
      border-radius: 50rpx;
      font-size: 36rpx;
      font-weight: 600;
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.15);
    }
  }
  
  .login-switch {
    text-align: center;
    margin-top: 40rpx;
    
    .switch-text {
      font-size: 28rpx;
      color: rgba(255, 255, 255, 0.8);
      text-decoration: underline;
    }
  }
}

.agreement-section {
  width: 100%;
  margin-top: 60rpx;
  
  .agreement-checkbox {
    display: flex;
    align-items: flex-start;
    
    .agreement-text {
      margin-left: 15rpx;
      font-size: 24rpx;
      color: rgba(255, 255, 255, 0.8);
      line-height: 1.6;
      
      .agreement-link {
        color: #ffd700;
        text-decoration: underline;
      }
    }
  }
}

.guest-section {
  margin-top: 60rpx;
  
  .guest-text {
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.6);
    text-decoration: underline;
  }
}

.footer-decoration {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 200rpx;
  
  .decoration-image {
    width: 100%;
    height: 100%;
    opacity: 0.3;
  }
}
</style>